package com.team9.fitness.service;

import com.team9.fitness.entity.CommentLike;
import com.team9.fitness.mapper.CommentLikeMapper;
import com.team9.fitness.mapper.PostCommentMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 评论点赞服务类
 * 
 * 提供评论点赞相关的业务逻辑：
 * - 点赞管理：点赞、取消点赞
 * - 状态查询：查询用户点赞状态
 * - 统计功能：统计评论点赞数量
 * - 事务管理：确保数据一致性
 */
@Slf4j
@Service
public class CommentLikeService {

    @Autowired
    private CommentLikeMapper commentLikeMapper;

    @Autowired
    private PostCommentMapper postCommentMapper;

    /**
     * 点赞评论
     */
    @Transactional
    public boolean likeComment(Long userId, Long commentId) {
        try {
            // 检查是否已经点赞
            CommentLike existingLike = commentLikeMapper.selectByUserIdAndCommentId(userId, commentId);
            
            if (existingLike != null && existingLike.getIsLiked()) {
                log.warn("用户已经点赞过该评论: userId={}, commentId={}", userId, commentId);
                return false;
            }

            // 创建或更新点赞记录
            CommentLike commentLike = CommentLike.builder()
                    .userId(userId)
                    .commentId(commentId)
                    .isLiked(true)
                    .build();
            commentLike.setCreatedAtIfNull();

            int result = commentLikeMapper.insertOrUpdate(commentLike);
            if (result > 0) {
                // 更新评论点赞数量
                int likeCount = commentLikeMapper.countLikesByCommentId(commentId);
                postCommentMapper.updateLikeCount(commentId, likeCount);
                
                log.info("评论点赞成功: userId={}, commentId={}, likeCount={}", userId, commentId, likeCount);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("评论点赞失败: userId={}, commentId={}", userId, commentId, e);
            return false;
        }
    }

    /**
     * 取消点赞评论
     */
    @Transactional
    public boolean unlikeComment(Long userId, Long commentId) {
        try {
            // 检查是否已经点赞
            CommentLike existingLike = commentLikeMapper.selectByUserIdAndCommentId(userId, commentId);
            
            if (existingLike == null || !existingLike.getIsLiked()) {
                log.warn("用户未点赞该评论: userId={}, commentId={}", userId, commentId);
                return false;
            }

            // 更新点赞状态为false
            int result = commentLikeMapper.updateLikeStatus(userId, commentId, false);
            if (result > 0) {
                // 更新评论点赞数量
                int likeCount = commentLikeMapper.countLikesByCommentId(commentId);
                postCommentMapper.updateLikeCount(commentId, likeCount);
                
                log.info("评论取消点赞成功: userId={}, commentId={}, likeCount={}", userId, commentId, likeCount);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("评论取消点赞失败: userId={}, commentId={}", userId, commentId, e);
            return false;
        }
    }

    /**
     * 切换评论点赞状态
     */
    @Transactional
    public boolean toggleCommentLike(Long userId, Long commentId) {
        try {
            CommentLike existingLike = commentLikeMapper.selectByUserIdAndCommentId(userId, commentId);
            
            if (existingLike != null && existingLike.getIsLiked()) {
                // 如果已点赞，则取消点赞
                return unlikeComment(userId, commentId);
            } else {
                // 如果未点赞，则点赞
                return likeComment(userId, commentId);
            }
        } catch (Exception e) {
            log.error("切换评论点赞状态失败: userId={}, commentId={}", userId, commentId, e);
            return false;
        }
    }

    /**
     * 获取用户点赞状态
     */
    public Boolean getUserLikeStatus(Long userId, Long commentId) {
        try {
            CommentLike commentLike = commentLikeMapper.selectByUserIdAndCommentId(userId, commentId);
            return commentLike != null ? commentLike.getIsLiked() : false;
        } catch (Exception e) {
            log.error("获取用户点赞状态失败: userId={}, commentId={}", userId, commentId, e);
            return false;
        }
    }

    /**
     * 获取评论点赞数量
     */
    public int getCommentLikeCount(Long commentId) {
        try {
            return commentLikeMapper.countLikesByCommentId(commentId);
        } catch (Exception e) {
            log.error("获取评论点赞数量失败: commentId={}", commentId, e);
            return 0;
        }
    }

    /**
     * 获取用户点赞的评论列表
     */
    public List<CommentLike> getUserLikedComments(Long userId) {
        try {
            return commentLikeMapper.selectLikedByUserId(userId);
        } catch (Exception e) {
            log.error("获取用户点赞评论列表失败: userId={}", userId, e);
            return List.of();
        }
    }

    /**
     * 获取评论点赞用户列表
     */
    public List<CommentLike> getCommentLikedUsers(Long commentId) {
        try {
            return commentLikeMapper.selectLikedByCommentId(commentId);
        } catch (Exception e) {
            log.error("获取评论点赞用户列表失败: commentId={}", commentId, e);
            return List.of();
        }
    }
}
